package br.com.blutufi.gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

import br.com.blutufi.model.Contact;

public class ContactsChatFrame extends JFrame {
	private static final long serialVersionUID = -2275624483497915891L;

	//width, height
	private static final int windowHeight = 300;

	private static final int historyWidth = 400;
	private static final int historyHeight = 150;

	private static final int messageWidth = 350;
	private static final int messageHeight = 100;

	private static final int contactsWidth = 250;
	private static final int contactsHeight = windowHeight;

	private static final Dimension windowDimension = new Dimension(historyWidth + contactsWidth,
			historyHeight + messageHeight);
	private static final Dimension historyDimension = new Dimension(historyWidth, historyHeight);
	private static final Dimension messageDimension = new Dimension(messageWidth, messageHeight);
	private static final Dimension contactsDimension = new Dimension(contactsWidth, contactsHeight);

	//	private JTextArea edtHistory;
	private JTextArea edtMessage;

	private JList lstContacts;

	private JButton sendButton;

	private JLabel lbHistory;
	private JLabel lbMessage;
	private JLabel lbContacts;

	//	private JScrollPane scrollHistory;
	private JScrollPane scrollMessage;
	private JScrollPane scrollContacts;

	private Listener listener;

	JTabbedPane tabbedPane;

	private String historyText = "JPO: Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\nVBR: Aenean commodo ligula eget dolor.\nJPO: Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\nVBR: Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.\nJPO: Nulla consequat massa quis enim.\nVBR: Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\n"
			+ "JPO: Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\nVBR: Aenean commodo ligula eget dolor.\nJPO: Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\nVBR: Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.\nJPO: Nulla consequat massa quis enim.\nVBR: Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\n"
			+ "JPO: Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\nVBR: Aenean commodo ligula eget dolor.\nJPO: Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\nVBR: Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.\nJPO: Nulla consequat massa quis enim.\nVBR: Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\n"
			+ "JPO: Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\nVBR: Aenean commodo ligula eget dolor.\nJPO: Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\nVBR: Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.\nJPO: Nulla consequat massa quis enim.\nVBR: Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.";
	//	private String[] contactList = {"JPO", "VBR", "MCN", "CAL"};
	private Contact[] contactList = { new Contact("JPO", "99999", historyText),
			new Contact("VBR", "9999999", "VBR: Lero\nVBR: LeroLero!"),
			new Contact("MCN", "123213123", "MCN: Vitor Budega?"), new Contact("CAL", "", "") };
	private final static String historyLbText = "Histórico";
	private final static String sendLbText = "Enviar";
	private final static String messageLbText = "Resposta";
	private final static String contactsLbText = "Contatos";
	private final static String frameTitle = "Bluetooth Message";

	private List<Contact> openedChats;

	private static ContactsChatFrame instace = new ContactsChatFrame();

	public static ContactsChatFrame getInstance() {
		return instace;
	}

	private ContactsChatFrame() {
		super(frameTitle);

		this.openedChats = new ArrayList<Contact>();

		initComponents();
		setupListeners();
	}

	private void initComponents() {
		JPanel componentsPanel = new JPanel(new GridBagLayout());

		//		this.edtHistory = new JTextArea(this.historyText);
		this.edtMessage = new JTextArea();

		this.lstContacts = new JList(this.contactList);

		this.sendButton = new JButton(ContactsChatFrame.sendLbText);

		this.lbHistory = new JLabel(ContactsChatFrame.historyLbText);
		this.lbMessage = new JLabel(ContactsChatFrame.messageLbText);
		this.lbContacts = new JLabel(ContactsChatFrame.contactsLbText);

		//		this.scrollHistory = new JScrollPane(edtHistory);
		this.scrollMessage = new JScrollPane(edtMessage);
		this.scrollContacts = new JScrollPane(lstContacts);

		this.listener = new Listener();

		this.tabbedPane = new JTabbedPane();
		this.tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

		//		this.tabbedPane.add(scrollHistory);

		GridBagConstraints c;
		c = new GridBagConstraints(0, 0, //gridx, gridy
				1, 1, //gridwidth, gridheight
				0, 0, // weightx, weighty,
				GridBagConstraints.NORTHWEST, //anchor
				GridBagConstraints.BOTH, //fill
				new Insets(0, 0, 0, 0), //insets
				0, 0 // ipadx, ipady
		);
		componentsPanel.add(lbHistory, c);

		c = new GridBagConstraints(historyWidth + 1, 0, //gridx, gridy
				1, 1, //gridwidth, gridheight
				0, 0, // weightx, weighty,
				GridBagConstraints.NORTHEAST, //anchor
				GridBagConstraints.HORIZONTAL, //fill
				new Insets(0, 0, 0, 0), //insets
				0, 0 // ipadx, ipady
		);
		componentsPanel.add(lbContacts, c);

		c = new GridBagConstraints(0, 1, //gridx, gridy
				historyWidth, historyHeight, //gridwidth, gridheight
				0.8, 1, // weightx, weighty,
				GridBagConstraints.WEST, //anchor
				GridBagConstraints.BOTH, //fill
				new Insets(0, 0, 0, 0), //insets
				0, 0 // ipadx, ipady
		);
		componentsPanel.add(tabbedPane, c);

		c = new GridBagConstraints(historyWidth + 1, 1, //gridx, gridy
				contactsWidth, contactsHeight, //gridwidth, gridheight
				0.2, 1, // weightx, weighty,
				GridBagConstraints.EAST, //anchor
				GridBagConstraints.BOTH, //fill
				new Insets(0, 0, 0, 0), //insets
				0, 0 // ipadx, ipady
		);
		componentsPanel.add(scrollContacts, c);

		c = new GridBagConstraints(0, historyHeight + 1, //gridx, gridy
				1, 1, //gridwidth, gridheight
				0, 0, // weightx, weighty,
				GridBagConstraints.SOUTHWEST, //anchor
				GridBagConstraints.HORIZONTAL, //fill
				new Insets(0, 0, 0, 0), //insets
				0, 0 // ipadx, ipady
		);
		componentsPanel.add(lbMessage, c);

		c = new GridBagConstraints(0, historyHeight + 2, //gridx, gridy
				messageWidth, messageHeight, //gridwidth, gridheight
				1, 0, // weightx, weighty,
				GridBagConstraints.LAST_LINE_START, //anchor
				GridBagConstraints.BOTH, //fill
				new Insets(0, 0, 0, 0), //insets
				0, 0 // ipadx, ipady
		);
		componentsPanel.add(scrollMessage, c);

		c = new GridBagConstraints(messageWidth + 1, historyHeight + 2, //gridx, gridy
				1, 1, //gridwidth, gridheight
				0, 0, // weightx, weighty,
				GridBagConstraints.PAGE_END, //anchor
				GridBagConstraints.NONE, //fill
				new Insets(5, 0, 5, 0), //insets
				0, 0 // ipadx, ipady
		);
		JPanel sendPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		sendPanel.add(sendButton);
		componentsPanel.add(sendPanel, c);

		//		this.scrollHistory.setPreferredSize(historyDimension);
		this.scrollMessage.setPreferredSize(messageDimension);
		this.scrollContacts.setPreferredSize(contactsDimension);
		this.setPreferredSize(windowDimension);
		this.setMinimumSize(windowDimension);

		this.add(componentsPanel);
		this.pack();
	}

	private void setupListeners() {
		this.sendButton.addActionListener(this.listener);
		this.lstContacts.addMouseListener(listener);

	}

	private void createNewTab() {
		int lstIndex = lstContacts.getSelectedIndex();
		Contact contact = contactList[lstIndex];
		int newIndex = tabbedPane.getTabCount();

		JTextArea txArea = new JTextArea(contact.getHistory());
		JScrollPane scrollPane = new JScrollPane(txArea);

		this.tabbedPane.add(contact.getName(), scrollPane);
		this.tabbedPane.setTabComponentAt(newIndex, new ButtonTabComponent(this.tabbedPane,
				openedChats));
		this.tabbedPane.setComponentAt(newIndex, new JScrollPane(
				new JTextArea(contact.getHistory())));

		Contact c = (Contact) lstContacts.getSelectedValue();
		openedChats.add(c);
		tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
	}

	public static void main(String[] args) {
		ContactsChatFrame c = new ContactsChatFrame();
		c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		c.setVisible(true);
	}

	class Listener implements ActionListener, MouseListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == ContactsChatFrame.this.sendButton) {
				// TODO: Send message
			}
		}

		@Override
		public void mouseClicked(MouseEvent e) {
			if (e.getSource() == lstContacts) {
				int index = lstContacts.getSelectedIndex();
				Contact contact = contactList[index];

				boolean found = false;
				if (e.getClickCount() >= 2) {
					for (Contact c : openedChats) {
						if (contact == c) {
							found = true;
							tabbedPane.setSelectedIndex(openedChats.indexOf(c));
							break;
						}
					}
					if (!found) {
						createNewTab();
					}
				}
			}
		}

		@Override
		public void mousePressed(MouseEvent e) {
		}

		@Override
		public void mouseReleased(MouseEvent e) {
		}

		@Override
		public void mouseEntered(MouseEvent e) {
		}

		@Override
		public void mouseExited(MouseEvent e) {
		}

	}
}